/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package connection;

import java.net.*;
import java.io.*;
import java.util.concurrent.*;
import protocol.Packet;


public class Server extends Thread{

    private ServerSocket server;
    private Socket socket;
    private Connection connection;


    public Server(Connection connection)throws IOException{
        this.connection = connection;
        InetAddress address = InetAddress.getLocalHost();
        server = new ServerSocket(0, 50, address);

        InetSocketAddress inetSocket = (InetSocketAddress)server.getLocalSocketAddress();

        FileOutputStream fileoutput = new FileOutputStream("lista_peer.txt", true);
        fileoutput.write((String.valueOf(inetSocket)+"\n").getBytes());
        fileoutput.close();

        System.out.println("Server creato  "+ inetSocket);
    }

    public SocketAddress getSocketAddress(){
        return server.getLocalSocketAddress();
    }

    public void run(){

        try{

            while(true){
                socket = server.accept();
                new ClientHandler(socket).start();
            }



        }catch(IOException e){
            System.err.println("Errrore in run");
        }

    }


    public class ClientHandler extends Thread{

    private ObjectInputStream objIn;
    private Socket socket;


    public ClientHandler(Socket socket)throws IOException{
            this.socket = socket;
           
            objIn = new ObjectInputStream(socket.getInputStream());

    }


    public void run(){

        while(true){
            try{

             Packet p = (Packet)objIn.readObject();
             if(p!=null)  connection.getQPackets().put(p);
          

            }catch(Exception e){
                //System.err.println("Errore in client handler");
               // e.printStackTrace();
            }

        }

    }



}

    }